package com.lemurian.bankdata.bean;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.lemurian.bankdata.bean.base.BaseDaoHibernate;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.entity.Certificate;

@Repository
public class CertificateDAO extends BaseDaoHibernate<Certificate> {
	
	private BankDataLogger log = BankDataLogger.getLogger(CertificateDAO.class.getName());

	public Certificate loadWithDebitur(int id){
		Certificate certificate = null;
		try {
			Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Certificate.class);
			criteria.createAlias("client", "client", Criteria.LEFT_JOIN);
			criteria.createAlias("client.debitur", "debitur", Criteria.LEFT_JOIN);
			criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
			criteria.add(Restrictions.eq("id", id));
			
			criteria.setCacheable(true);
			
			certificate = (Certificate) criteria.uniqueResult();
			
			if (certificate != null) {
				log.sInfo("Certificate found");
				if (certificate.getClient() != null) {
					log.sInfo("Certificate was assigned to somebody");
					if (certificate.getClient().getDebitur() != null) {
						log.sInfo("That somebody is [%s]", certificate.getClient().getDebitur().getName());
					}
				}
			}
					
			return certificate;
		} catch(Exception e){
			e.printStackTrace();
		}
		return certificate;
	}
}